package com.bruce.li.service.impl;

import com.alibaba.fastjson.JSON;
import com.bruce.li.mapper.SkuMapper;
import com.bruce.li.pojo.Sku;
import com.bruce.li.service.SkuService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class SkuServiceImpl implements SkuService {

//    private int currentPage = 1;

    private int pageSize = 1000;

    private int total;

    private String mappings = "{\n" +
            "  \"mappings\": {\n" +
            "    \"properties\": {\n" +
            "      \"id\":{\n" +
            "        \"type\":\"keyword\"\n" +
            "      },\n" +
            "      \"name\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\"\n" +
            "      },\n" +
            "      \"price\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"num\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"image\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"updateTime\":{\n" +
            "        \"type\": \"date\"\n" +
            "      },\n" +
            "      \"categoryId\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"categoryName\":{\n" +
            "        \"type\": \"text\"\n" +
            "      },\n" +
            "      \"brandName\":{\n" +
            "        \"type\": \"text\"\n" +
            "      },\n" +
            "      \"saleNum\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"commentNum\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";

    static RestHighLevelClient client;

    static {
        client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.133.40",9200,"http")));
    }


    @Autowired
    private SkuMapper skuMapper;

    @Override
    public boolean findSkuByPage(String index) throws IOException {

        //创建查询索引库请求
        GetIndexRequest getIndexRequest = new GetIndexRequest(index);
        //判断当前查询索引库是否存在
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);

        if (exists){
            //如果存在则删除
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
            //发请求删除
            client.indices().delete(deleteIndexRequest,RequestOptions.DEFAULT);
            //创建索引库和映射
            CreateIndexRequest createIndexRequest = myCreateIndex(index);
            //发送请求创建
            client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            //批处理
            findPage(index);
        }else {
            //不存在，直接批处理创建doc
            findPage(index);
        }

        return true;
    }


    public CreateIndexRequest myCreateIndex(String index){
        CreateIndexRequest request = new CreateIndexRequest(index);
        request.source(mappings, XContentType.JSON);
        return request;
    }

    public void findPage(String index) throws IOException {
        int total = skuMapper.findSukTotal();
        int ceil = (int) Math.ceil((total * 1.0) / pageSize);
        for (int currentPage = 1; currentPage <= ceil; currentPage++) {
            Integer pageIndex = pageSize*(currentPage-1);
            List<Sku> sukByPage = skuMapper.findSukByPage(pageIndex, pageSize);
            BulkRequest bulkRequest = new BulkRequest();
            for (Sku sku : sukByPage) {
                bulkRequest.add(new IndexRequest(index)
                .id(sku.getId())
                .source(JSON.toJSONString(sku),XContentType.JSON)
                );
            }
            BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            System.out.println(bulk);
        }
    }
}
